package logger

import (
	"fmt"
	"os"
	"time"

	retalog "github.com/lestrrat-go/file-rotatelogs"
	"github.com/rifflock/lfshook"
	"github.com/sirupsen/logrus"
)

// ConfigureLogger 配置日志
func ConfigureLogger() (*logrus.Logger, error) {
	logFilePath := "logs/log.log"
	linkName := "latest_log.log"

	// 确保logs目录存在
	if err := os.MkdirAll("logs", os.ModePerm); err != nil {
		return nil, fmt.Errorf("failed to create logs directory: %w", err)
	}
	// 创建日志文件
	src, err := os.OpenFile(logFilePath, os.O_RDWR|os.O_CREATE, 0755)
	if err != nil {
		return nil, fmt.Errorf("failed to open log file: %w", err)
	}

	// 创建日志实例
	logger := logrus.New()
	// 输出
	logger.Out = src
	// 设置日志级别
	logger.SetLevel(logrus.DebugLevel)
	// 设置日志格式
	logger.SetFormatter(&logrus.TextFormatter{DisableColors: true, TimestampFormat: "2006-01-02 15:04:05"})

	// 添加时间分割
	logWriter, err := retalog.New(
		logFilePath+".%Y-%m-%d.log",            // 日志文件名
		retalog.WithMaxAge(7*24*time.Hour),     // 最大保存时间
		retalog.WithRotationTime(24*time.Hour), // 日志切割时间间隔
		retalog.WithLinkName(linkName),         // 软连接
	)
	if err != nil {
		return nil, fmt.Errorf("failed to create rotated log writer: %w", err)
	}

	// 创建 WriterMap
	writeMap := lfshook.WriterMap{
		logrus.InfoLevel:  logWriter,
		logrus.ErrorLevel: logWriter,
		logrus.FatalLevel: logWriter,
		logrus.DebugLevel: logWriter,
	}

	// 实例化 Hook
	hook := lfshook.NewHook(writeMap, &logrus.JSONFormatter{
		TimestampFormat: "2006-01-02 15:04:05",
	})

	// 添加 Hook 到 logger
	logger.AddHook(hook)

	return logger, nil
}
